<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\common\model\addon;

use app\common\model\BaseModel;

class AddonConfig extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    protected $type = array(
        'config' => 'json'
    );

    // 添加配置

    public function add($name, $config, $addon_name = '', $plaid = '')
    {
        $addon_name = $addon_name ?: get_addon();
        $plaid = $plaid ?: get_plaid();
        if (!$addon_name) {
            return false;
        }
        $res = $this
            ->where('name', $name)
            ->where('addon_name', $addon_name)
            ->where('plaid', get_plaid())
            ->findOrEmpty();

        $res->save([
            'name'       => $name,
            'config'     => $config,
            'addon_name' => $addon_name,
            'plaid'      => $plaid
        ]);
        return true;
    }

    public function get($name, $addon_name = '', $plaid = '')
    {
        $addon_name = $addon_name ?: get_addon();
        $plaid = $plaid ?: get_plaid();
        if (!$addon_name) {
            return false;
        }
        $res = $this
            ->where('name', $name)
            ->where('addon_name', $addon_name)
            ->where('plaid', $plaid)
            ->findOrEmpty();
        return $res->config;
    }

    public function del($name, $addon_name = '', $plaid = '')
    {
        $addon_name = $addon_name ?: get_addon();
        $plaid = $plaid ?: get_plaid();
        if (!$addon_name) {
            return false;
        }
        $res = $this
            ->where('name', $name)
            ->where('addon_name', $addon_name)
            ->where('plaid', $plaid)
            ->findOrEmpty();
        $res->delete();
        return true;
    }

    public function clear($addon_name)
    {
        $this->where('addon_name', $addon_name)->delete();
    }
}
